﻿using MetroDataApi.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MetroDataApi.Controllers.DataQueryTable
{
    public class SummaryTableController : Controller
    {
        private JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings()
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver(),
            Converters = new List<JsonConverter> { new MyDateTimeConvertor() }
        };

        public ActionResult Index(int prjId, string location = "上行线",
            string monitorType = "沉降", string endTime = "", string startTime = "", string json = "0")
        {
            if (json == "1")
            {
                return RedirectToAction("Json", new
                {
                    prjId = prjId,
                    location = location,
                    monitorType = monitorType,
                    endTime = endTime,
                    startTime = startTime
                });
            }
            else
            {
                ViewBag.Item = this.getSummary(prjId, location, monitorType, endTime, startTime);
                return View();
            }
        }

        public ContentResult Json(int prjId, string location = "",
            string monitorType = "", string endTime = "", string startTime = "", string json = "0")
        {
            var Item = this.getSummary(prjId, location, monitorType, endTime, startTime);
            return Content(JsonConvert.SerializeObject(Item, Formatting.Indented, jsonSerializerSettings), "application/json");
        }

        private recentChanges getSummary(int prjId, string location = "",
            string monitorType = "", string endTime = "", string startTime = "")
        {
            using (var db = new MetroDataDataContext())
            {

                if (location == "" || monitorType == "")
                {
                    var ptDict = db.MonitorPointsDictionary.Where(p => p.PrjId == prjId).First();
                    location = ptDict.Location;
                    monitorType = ptDict.MonitorType;
                }
                var times = Recent2Changes.get2Times(prjId, location, monitorType, startTime, endTime);

                var recentChange = Recent2Changes.GetChanges(prjId, monitorType, location, times[0], times[1]);
                recentChange.summary();
                return recentChange;
            }
        }

    }
}
